<?php
/**
 * @特惠赚
 * Author: 小谢     
 * Date: 2019-5-13
 */
namespace app\admin\controller;
use app\admin\logic\GoodsLogic;
use app\admin\logic\TaobaoLogic;
use think\facade\Session;
use think\captcha\Captcha;
use think\facade\View;
use think\Db;

class Goods extends Base {

    /**
     *  商品分类列表
     */
    public function categoryList(){                
        $GoodsLogic = new GoodsLogic();            
        $cat_list = $GoodsLogic->goods_cat_list();    
        View::share(['cat_list'=>$cat_list]);
        return View('categoryList');
    }
    
    /**
     * 添加修改商品分类
     */
    public function addEditCategory(){
             
            $GoodsLogic = new GoodsLogic();   
            if(I('get.cate_id'))
            {
                $goods_category_info = M('GoodsCategory')->where('id='.I('get.cate_id',0))->find();
                $all_type = M('goods_category')->where("level<3")->getField('id,name,parent_id');//上级分类数据集，限制3级分类，那么只拿前两级作为上级选择
                if(!empty($all_type)){
                	$parent_id  = empty($goods_category_info) ? I('parent_id',0) : $goods_category_info['parent_id'];
                	$all_type   = $GoodsLogic->getCatTree($all_type);
                	$cat_select = $GoodsLogic->exportTree($all_type,0,$parent_id);
                	
                }
                View::share(["goods_category_info"=>$goods_category_info,"cat_select"=>$cat_select]);
                return View('_category');
            }

            //提交数据
            if(I('post.')) {
                $data = I('post.');
                $checkData = ['name'=>$data['name'],'sort_order'=>$data['sort_order']];
                //验证数据、分类名、排序
                $validate = new \app\admin\validate\GoodsCategory();
                if (!$validate->check($checkData)){
                      $this->error($validate->getError(),'/Admin/goods/categoryList');
                } else {
                    
                    //查找同级分类是否有重复分类
                    $par_id = ($data['parent_id'] > 0) ? $data['parent_id'] : 0;
                    $sameCateWhere = ['parent_id'=>$par_id , 'name'=>$data['name']];
                    $data['id'] && $sameCateWhere['id'] = array('<>' , $data['id']);
                    $same_cate = M('GoodsCategory')->where($sameCateWhere)->find();

                    if($same_cate){
                        $return_arr = array('status' => 0,'msg' => '同级已有相同分类存在');
                    }

                    
                    if ($data['id'] > 0 && $data['parent_id'] == $data['id']) {
                        //  编辑
                        $return_arr = array('status' => 0,'msg' => '上级分类不能为自己');
                    }

                    //判断不能为自己的子类
                    if ($data['id'] > 0) {
                        $category_id_list = db('goods_category')->where('parent_id',$data['id'])->field('id')->select();
                        $category_id_list = array_column($category_id_list,'id');
                        if (in_array($data['parent_id'],$category_id_list)) {
                            $return_arr = array('status' => 0,'msg' => '上级分类不能为自己的子类');
                        }
                    }

                    if ($data['id'] > 0)
                    {
                        M('GoodsCategory')->where(['id'=>$data['id']])->save($data);
                        $GoodsLogic->refresh_cat(I('id'));
                    }
                    else
                    {
                        $insert_id = M('GoodsCategory')->insertGetId($data);
                        $GoodsLogic->refresh_cat($insert_id);
                    }

                    if(isset($return_arr) && $return_arr['status'] == 0) {
                        $this->error($return_arr['msg'],'/Admin/goods/categoryList');
                    }
                    $this->success('操作成功','/Admin/goods/categoryList');
                }  
            }
            $all_type = M('goods_category')->where("level<3")->getField('id,name,parent_id');//上级分类数据集，限制3级分类，那么只拿前两级作为上级选择
            if(!empty($all_type)){
                $parent_id  = !empty(I('parent_id',0)) ? I('parent_id',0) : 0;
                $all_type   = $GoodsLogic->getCatTree($all_type);
                $cat_select = $GoodsLogic->exportTree($all_type,0,$parent_id); 
            }
            View::share(['cat_select'=> isset($cat_select) ? $cat_select : []]);
            return View('_category');
    }

    /**
     * 删除分类
     */
    public function delGoodsCategory(){
        $ids = I('post.ids','');
        empty($ids) &&  $this->ajaxReturn(['status' => -1,'msg' =>"非法操作！",'data'  =>'']);
        // 判断子分类
        $count = Db::name("goods_category")->where("parent_id = {$ids}")->count("id");
        $count > 0 && $this->ajaxReturn(['status' => -1,'msg' =>'该分类下还有分类不得删除!']);
        // 判断是否存在商品
        $goods_count = Db::name('Goods')->where("cate_id = {$ids}")->count('1');
        $goods_count > 0 && $this->ajaxReturn(['status' => -1,'msg' =>'该分类下有商品不得删除!']);
        // 删除分类
        DB::name('goods_category')->where('id',$ids)->delete();
        $this->ajaxReturn(['status' => 1,'msg' =>'操作成功','url'=>U('Admin/Goods/categoryList')]);
    }
    
    
    /**
     *  商品列表
     */
    public function goodsList() { 
        $start_time  = strtotime(I('start_time'));
        $end_time    = strtotime(I('end_time'));
        $keyword     = I('keyword');
        $cate_id     = I('cate_id');//分类ID
        
        $where = '';
        if (!empty($start_time) && !empty($end_time)) {
            $where = " g.add_time >= ".$start_time." AND ". " g.add_time <=".$end_time;
        }

        if (!empty($where) && $keyword && $cate_id >0) {
             $where.= ' AND g.num_iid LIKE '.'"%'.$keyword.'%"'. ' OR g.title LIKE '. '"%'.$keyword.'%"';
             $where.= ' AND cate_id='.$cate_id;
        } else if (!empty($where) && $keyword) {
             $where.= ' AND g.num_iid LIKE '.'"%'.$keyword.'%"'. ' OR g.title LIKE '. '"%'.$keyword.'%"';
        } else if(!empty($where) && $cate_id >0) {
             $where.= ' AND cate_id='.$cate_id;
        } else {
             $where = "1=1";
        }

        $p = I('p/d',1);
        $list = M('goods')->alias('g')->join('__GOODS_CATEGORY__ c','g.cate_id = c.id')->where($where)->order('order_sort ASC')->page($p.',20')->paginate(20);
        $count = $list->count();
        //第三级分类
        $category = M('goods_category')->where(['level'=>3])->select();
        View::share([
            'list'=> isset($list) ?  $list : array(),
            "stime"=>time(),
            'etime'=>time()+3600*24 *365,
            "count"=>isset($count) ? $count : 0,
            "category"=>$category
         ]);
        return View('goodsList');
    }
    

    /**
     * 添加修改商品
     */
    public function addEditGoods() {
        $GoodsLogic = new GoodsLogic();
        $goods_id = input('id');
        if($goods_id){
            $goods = M('goods')->where('goods_id', $goods_id)->find();
            $level_cat = $GoodsLogic->find_parent_cat($goods['cate_id']); // 获取分类默认选中的下拉框
            //查找第二级分类
            $arr_cat['cat2'] = M('goods_category')->where(['id'=>$level_cat[2]])->column('id,name');
            if(isset($level_cat[3])) {
                $arr_cat['cat3'] = M('goods_category')->where(['id'=>$level_cat[3]])->column('id,name');
            }
            View::share(['level_cat'=>$level_cat,'goods_info'=>$goods,'arr_cat'=>$arr_cat]);
        }
        $cat_list = Db::name('goods_category')->where("parent_id = 0")->select(); // 已经改成联动菜单
        View::share(['goods_info'=>[],'cat_list'=>$cat_list]);
        return View('_goods');
    }

    //商品保存
    public function save(){
        $data = input('post.');
        if($data) {
            $validate = new \app\admin\validate\Goods();
            if (!$validate->check($data)){
                 $this->error($validate->getError());
            }
        }

        //编辑商品
        if (isset($data['goods_id']) && $data['goods_id'] > 0) { 
            $data['small_images'] = $data['small_images'];
            $data['add_time'] = time();
            $data['click_url'] = $data['http_link'];
            $data['desc'] = $data['pic_url'];
            unset($data['http_link']);
            $result = M('goods')->where(['goods_id'=>$data['goods_id']])->save($data);
        } else {
            //添加商品
            $data['small_images'] = serialize(explode("##",$data['small_images']));
            $data['add_time'] = time();
            $data['click_url'] = $data['http_link'];
            $data['desc'] = $data['pic_url'];
            unset($data['http_link']);
            $result = M('goods')->add($data);
        }

        if(isset($result)) {
            $this->success('操作成功',U('/Admin/Goods/goodsList'));
        }
        $this->error('操作失败',U('/Admin/Goods/goodsList'));
    }

    /*
     * 获取下级分类
     */
    public function get_category(){
        $parent_id = I('get.parent_id/d'); // 商品分类 父id
        $list = M('goods_category')->where("parent_id", $parent_id)->select();
        if ($list) {
            $this->ajaxReturn(['status' => 1, 'msg' => '获取成功！', 'result' => $list]);
        }
        $this->ajaxReturn(['status' => -1, 'msg' => '获取失败！', 'result' =>[]]);
    }
    
    /**
     * [getTaboaGoods ]  返回采集商品信息
     * @return [type] [description]
     */
    public function getTaboaGoods() {
        $url  = I('post.http_link');
        //判断是否淘宝、天猫链接
        if (strpos($url, "taobao.com") || strpos($url, "tmall.com")) {
            $parse_url = parse_url($url);
            $arr_info = $this->convertUrlQuery($parse_url["query"]);
            $data = [];
            //替代$k下标amp;字符
            if(is_array($arr_info)) {
                foreach ($arr_info as  $k=>$v) {
                    $data[str_replace("amp;","", $k)] = $v;
                }
            }
            //采集num_iid
            $itemid  = isset($data['itemid']) ? $data['itemid'] : 0 ;
            $num_iid = isset($data['id']) ? $data['id'] : $itemid;
            $res = M('goods')->where(["num_iid" =>$num_iid])->count();
            if ($res) {
                $this->ajaxReturn(['status' => 0,'error_info' =>'商品已存在！']);
            } else {
                $TaobaoLogic = new TaobaoLogic();
                $goods_arr = $TaobaoLogic->getTaobaoGoods($num_iid);
                isset($goods_arr['code']) && $this->ajaxReturn(['status'=>0,'error_info'=>$goods_arr['sub_code'].':'.$goods_arr['sub_msg']]);
                //重新组装商品数组信息
                $goods_info = [];
                if (is_array($goods_arr)) {
                    $goods_info = [
                         "num_iid"=>$goods_arr['num_iid'],
                         "pict_url"=>$goods_arr['pict_url'],
                         "small_images"=>$goods_arr['small_images']['string'],
                         "title_name"=>$goods_arr['title'],
                         "volume"=>$goods_arr['volume'],
                         "price"=>$goods_arr['reserve_price'],
                         "discount_price"=>$goods_arr['zk_final_price']
                    ];
                    $this->ajaxReturn(['status'=>1,'info'=>$goods_info]);
                }
                $this->ajaxReturn(['status'=>0,'error_info'=>'暂无数据']);
            }
        }
    }

    /**
     * [convertUrlQuery description]
     * @param  String $str  拼接字符串
     * @return Array
     */
    public function convertUrlQuery($str) {
        $explode_arr = explode("&", $str);
        $data = [];
        foreach ($explode_arr as $v) {
            $explode_val = explode("=", $v);
            $data[$explode_val[0]] = $explode_val[1];
        }
        return $data;
    }
    
}